package com.sugou.web.ctrl;

import java.io.File;
import java.io.PrintWriter;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.codehaus.jackson.map.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.sugou.dao.support.Pages;
import com.sugou.dao.support.bean.PagesSearchStatement;
import com.sugou.services.support.Service;
import com.sugou.system.var.GlobalVars;

/**
 * 父Controller支持类
 * @author 童弘成
 */
public class WebControllerSupport implements Serializable{
	private static final long serialVersionUID = 29539144152126645L;
	
	protected static Logger logger = LoggerFactory.getLogger(WebControllerSupport.class);
	
	private static final String VIEW_REDIRECT_PREFIX = "redirect:";
	
	/**
	 * 返回消息
	 */
	protected Map<String, Object> msg=new HashMap<String, Object>();
	
	protected List<Map<String, Object>> datas=new ArrayList<Map<String,Object>>();
	
	@Resource(name="baseService")
	protected Service<Serializable> service;
	
	public static final Pattern LIMIT_REGEX=Pattern.compile("^(\\d+)-(\\d+)$");
	public static final Pattern NUMBER_REGEX=Pattern.compile("^\\d+$");
	/**
	 * json转换类
	 */
	protected ObjectMapper jsonMapper=new ObjectMapper();
	
	@Resource
	protected HttpServletRequest request;
	
	protected HttpServletResponse response=(HttpServletResponse) GlobalVars.getVar("response");
	
	protected String createRedirectViewPath(String path) {
        StringBuilder builder = new StringBuilder();
        builder.append(VIEW_REDIRECT_PREFIX);
        builder.append(path);
        return builder.toString();
    }
	
	/**
	 * 转为json数据格式
	 * @param value 转换对象
	 * @return json字符串
	 */
	protected void toJSON(Object value) {
		try{
			HttpServletResponse response=this.response;
			response.setCharacterEncoding("utf-8");
			response.setContentType("application/json;charset=utf-8");
			//处理Ajax GET提交有无缓存问题
			response.setHeader("Cache-Control", "no-cache");   
			PrintWriter writer=response.getWriter();
			String out=this.jsonMapper.writeValueAsString(value);
			writer.println(out);
			writer.close();
		}catch(Exception e){
			ControllerException webex=new ControllerException(e);
			logger.error(webex.getMessage(), webex);
			throw webex;
		}
	}
	
	/**
	 * 获得json返回信息。
	 */
	protected void writeMessage(String msg) {
		try{
			HttpServletResponse response=this.response;
			
			response.setCharacterEncoding("utf-8");
			response.setContentType("text/html; charset=utf-8");
			//处理Ajax GET提交有无缓存问题
			response.setHeader("Cache-Control", "no-cache"); 
			PrintWriter writer=response.getWriter();
			writer.write(msg);
			writer.flush();
			writer.close();
		}catch(Exception e){
			ControllerException webex=new ControllerException(e);
			logger.error(webex.getMessage(), webex);
			throw webex;
		}
	}
	
	/**
	 * 获得json返回信息。
	 */
	protected void writeMessage() {
		this.toJSON(this.msg);
	}
	/**
	 * 获得json返回信息。
	 */
	protected void writeDatas() {
		this.toJSON(this.datas);
	}
	/**
	 * 获得提交参数
	 */
	protected String getParam(String paramName){
		return this.request.getParameter(paramName);
	}
	
	protected String[] getParamValues(String paramName){
		return this.request.getParameterValues(paramName);
	}
	
	public static final Pattern PATH_PAGES_REGEX=Pattern.compile("^(.*)/(\\d+)$");
	
	protected Pages createPagesSearchByPathVar(String content,List<Serializable> params,int size){
		HashMap<String, Serializable> tags=new HashMap<String, Serializable>();
		String path=this.request.getServletPath();
		Matcher m=PATH_PAGES_REGEX.matcher(path);
		Pages pages=null;
		if(m.matches()){
			tags.put("curpath", m.group(1));
			pages=new PagesSearchStatement(content, params, Integer.parseInt(m.group(2)), size, tags);
		}else{
			tags.put("curpath",path);
			pages=new PagesSearchStatement(content, params, 1, size, tags);
		}
		
		return pages;
	}
}
